package com.hlkj.baojin.utils.hik;

import com.ivms6.core.util.CollectionUtils;
import com.ivms6.core.util.XMLUtils;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class XmlUtil {
	
	private static Document doc=null;
	
	public static void parseXml(String xml) throws Exception{
		if (ObjectUtils.isStringEmpty(xml) || "null".equalsIgnoreCase(xml)) {
			throw new Exception("xml数据为空");
		}
		File xmlFile=new File(xml);
		if(xmlFile.exists()){
			 SAXReader reader = new SAXReader(); 
			 try {
				doc = reader.read(xmlFile);
			} catch (DocumentException e) {
				LogUtil.logError(XmlUtil.class, e,"xml文件格式不正确");
			}
		}else{
			try {
				doc = DocumentHelper.parseText(xml);
			} catch (DocumentException e) {
				LogUtil.logError(XmlUtil.class, e,"xml字符串格式不正确");
			}
		}
	}
	
	
	public static  Map<String, String> xmlToMapForItms(Document doc,String keyString ,String value) {
		Map<String, String> map = new HashMap<String, String>();

		try {

			 

			Element root = (Element) doc.getRootElement(); // 获取XML文档的根节点对象

			@SuppressWarnings("unchecked")
			List<Element> list = root.elements(); // 获取根节点下的所有的子节点

			for (Element ele : list) { // 遍历根节点下的所有子节点并将其放入MAP对象中

				map.put(ele.attributeValue(keyString), ele.attributeValue(value));

			}

		} catch (Exception e) {

			e.printStackTrace();

		}
		return map;
	}

	/**
	 * 执行WebService远程过程调用，并从中获取多行XML元素数据
	 * 
	 * @author chixueshun 2014-3-10 上午9:54:14
	 * @param client
	 * @param method
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static List<Element> getRows() throws Exception {
		//String xml = client.call(String.class, method, args);
		//LogUtil.logInfo(CommonService.class, "getResources XML:", xml);
		//Document doc = DocumentHelper.parseText(xml);
		Element root = doc.getRootElement();
		Element head = root.element("head");
		if (head == null) {
			throw new Exception("信息格式有误");
		}
		Element result = head.element("result");
		if (result == null) {
			throw new Exception("信息格式有误");
		}
		if (!WebServiceConstant.WS_RESULT_CODE_SUCCESS.equals(result.attributeValue("result_code"))) {
			throw new Exception(result.attributeValue("message"));
		}
		Element rows = root.element("rows");
		if (rows == null) {
			throw new Exception("信息格式有误");
		}
		return rows.elements("row");
	}
	/**
	 * 执行WebService远程过程调用，并从中获取单行业务实体数据
	 * 
	 * @author chixueshun 2014-3-10 上午9:56:02
	 * @param clazz
	 * @param client
	 * @param method
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static <T> T getVo(Class<T> clazz) throws Exception {
		List<Element> list = getRows();
		if (list != null && list.size() > 0) {
			return fromElement(clazz, list.get(0));
		}
		return null;
	}
	/**
	 * 执行WebService远程过程调用，并从中获取多行业务实体数据
	 * 
	 * @author chixueshun 2014-3-10 上午9:55:34
	 * @param clazz
	 * @param client
	 * @param method
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static <T> List<T> getVos(Class<T> clazz)
			throws Exception {
		List<T> voList = new ArrayList<T>();
		List<Element> list = getRows();
		for (Element row : list) {
			voList.add(fromElement(clazz, row));
		}
		return voList;
	}
	
	/**
	 * 获得字符串属性
	 * 
	 * @author chixueshun 2014-3-10 上午9:58:17
	 * @param e
	 * @param name
	 * @return
	 */
	public static String getStringAttr(Element e, String name) {
		String val = e.attributeValue(name);
		return val == null || val.equals("null") ? null : val;
	}

	/**
	 * 获得整型属性
	 * 
	 * @author chixueshun 2014-3-10 上午9:58:29
	 * @param e
	 * @param name
	 * @return
	 */
	public static Integer getIntAttr(Element e, String name) {
		String val = e.attributeValue(name);
		return val == null || val.equals("null") ? null : Integer.parseInt(val);
	}

	/**
	 * 获得长整型属性
	 * 
	 * @author chixueshun 2014-3-10 上午9:58:39
	 * @param e
	 * @param name
	 * @return
	 */
	public static Long getLongAttr(Element e, String name) {
		String val = e.attributeValue(name);
		return val == null || val.equals("null") ? null : Long.parseLong(val);
	}
	/**
	 * 将XML元素转换为业务实体
	 * 
	 * @author chixueshun 2014-3-10 上午9:58:54
	 * @param cls
	 * @param ele
	 * @return
	 */
	public static <T> T fromElement(Class<T> cls, Element ele) {
		if (cls == null || ele == null) {
			throw new IllegalArgumentException("参数有误！");
		}
		try {
			T o = cls.newInstance();
			List<Attribute> attrs = ele.attributes();// 信息包含在属性中
			for (Attribute attr : attrs) {
				String attrName = attr.getName();
				if (attrName.startsWith("i_") || attrName.startsWith("c_")) {// 去掉前缀：java属性的定义一般不加前缀
					attrName = attrName.substring(2);
				}
				String temp = StringUtils.toHumpCasing(attrName);// 去掉下划线，转换为驼峰式命名
				String fieldName = temp.substring(0, 1).toLowerCase() + temp.substring(1);
				String setMethodName = "set" + temp.substring(0, 1).toUpperCase() + temp.substring(1);
				;// 得到set方法
				String attrVal = attr.getValue();
				try {
					Field field = null;
					Class clazz = cls;
					while (clazz != Object.class) {// 遍历当前类及其所有父类，查找set方法
						try {
							field = clazz.getDeclaredField(fieldName);
							if (field != null) {
								break;
							}
						} catch (NoSuchFieldException e) {
							clazz = clazz.getSuperclass();
						}
					}
					if (field == null) {
						continue;
					}
					Class fieldType = field.getType();
					Method method = clazz.getMethod(setMethodName, fieldType);
					if (method != null) {
						Object val = attrVal == null || attrVal.equals("null") ? null : CommonFun.parseObject(fieldType,
								attrVal);
						method.invoke(o, val);// 设置属性值
					}
				} catch (SecurityException e) {
					LogUtil.logError(XmlUtil.class, e);
				} catch (NoSuchMethodException e) {
					LogUtil.logDebug(XmlUtil.class, setMethodName + "方法不存在");
				} catch (Exception e) {
					LogUtil.logError(XmlUtil.class, e);
				}
			}
			return o;
		} catch (InstantiationException e) {
			LogUtil.logError(XmlUtil.class, e);
		} catch (IllegalAccessException e) {
			LogUtil.logError(XmlUtil.class, e);
		}
		return null;
	}
	public static String getRowAttrByIoXml(String resXml, String attrName) {
		Document doc = null;
		try {
			doc = XMLUtils.convertStringToXml(resXml);
		} catch (DocumentException e) {
			LogUtil.logError(XmlUtil.class, e);
		}

		List<Element> rows = XMLUtils
				.getElementsByXPath(doc, "/table/rows/row");
		if (CollectionUtils.isNotEmpty(rows)) {
			Element e = rows.get(0);
			String attributeValue = e.attributeValue(attrName);
			return attributeValue;
		}

		return "0";
	}
//	public static void main(String[] args) {
//		
//
//		      try {
//		    	
//		    	  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//		            DocumentBuilder db = factory.newDocumentBuilder();
//		            InputStream in = ConfigUtil.class.getResourceAsStream("/resource/ItmsAlarmType.xml");  
//		        
//		  		SAXReader sax=new SAXReader(); //创建解析器
//
//
//		  		Document doc=sax.read(in); //创建对应的Document对象
//		  		Map<String,String> m = new LinkedHashMap<String, String>();
//		  		m =xmlToMap(doc);
//		    	  Element root=doc.getRootElement(); //获取XML文档的根节点对象
//
//
//		    	  List<Element> list = root.elements();  //获取根节点下的所有的子节点 
//			} catch (Exception e) {
//				System.out.println("webservice调用失败");
//			}
//		     try {
//				List<Element> list=XmlUtil.getRows();
//				if(null!=list && list.size()>0){
//					System.out.println(XmlUtil.getStringAttr(list.get(0), "tgc"));
//				}
//			} catch (Exception e) {
//				System.out.println("webservice 返回错误信息");
//			}
//    }  
//	}
}
